<template>
  <view class="container">
    <scroll-view v-if="step === 1" class="content" scroll-y>
      <!-- 分类选择 -->
      <view class="category-grid">
        <view
          v-for="category in appStore.mainCategories"
          :key="category.id"
          class="category-item"
          :class="{ active: selectedCategory?.id === category.id }"
          @click="selectCategory(category)"
        >
          <view class="category-icon">
            <text>{{ category.icon || category.name[0] }}</text>
          </view>
          <text class="category-name">{{ category.name }}</text>
        </view>
      </view>
    </scroll-view>

    <scroll-view v-else class="content" scroll-y>
      <!-- 二级分类（如果有） -->
      <view v-if="subCategories.length > 0" class="sub-category-section">
        <text class="label">选择类型</text>
        <view class="sub-category-list">
          <view
            v-for="sub in subCategories"
            :key="sub.id"
            class="sub-category-item"
            :class="{ active: selectedSubCategory?.id === sub.id }"
            @click="selectedSubCategory = sub"
          >
            {{ sub.name }}
          </view>
        </view>
      </view>

      <!-- 标题（可选） -->
      <view class="form-section">
        <text class="label">标题（选填）</text>
        <u-input
          v-model="form.title"
          placeholder="简短描述你的信息"
          maxlength="50"
          :show-word-limit="true"
        />
      </view>

      <!-- 内容描述 -->
      <view class="form-section">
        <text class="label required">详细描述</text>
        <u-textarea
          v-model="form.content"
          placeholder="描述一下您的信息..."
          maxlength="500"
          :show-word-limit="true"
          height="200"
        />
      </view>

      <!-- 媒体上传 -->
      <view class="form-section">
        <text class="label">添加图片或视频</text>
        <view class="media-upload">
          <view v-if="!form.videoUrl" class="image-list">
            <view v-for="(img, index) in form.imageUrls" :key="index" class="image-item">
              <image :src="img" class="upload-image" mode="aspectFill" />
              <view class="delete-btn" @click="removeImage(index)">
                <u-icon name="close" size="16" color="#fff"></u-icon>
              </view>
            </view>
            <view
              v-if="form.imageUrls.length < imageLimit"
              class="upload-btn"
              @click="chooseImage"
            >
              <u-icon name="camera" size="32" color="#999"></u-icon>
              <text>{{ form.imageUrls.length }}/{{ imageLimit }}</text>
            </view>
          </view>

          <view v-if="form.imageUrls.length === 0 && !form.videoUrl" class="video-upload">
            <view class="upload-btn" @click="chooseVideo">
              <u-icon name="play-circle" size="32" color="#999"></u-icon>
              <text>上传视频</text>
            </view>
          </view>

          <view v-if="form.videoUrl" class="video-preview">
            <video :src="form.videoUrl" class="upload-video" />
            <view class="delete-btn" @click="form.videoUrl = ''">
              <u-icon name="close" size="16" color="#fff"></u-icon>
            </view>
          </view>
        </view>
      </view>

      <!-- 价格（可选） -->
      <view class="form-section">
        <text class="label">价格（选填）</text>
        <view class="price-input">
          <u-input v-model="form.price" type="digit" placeholder="输入价格" />
          <u-input v-model="form.priceUnit" placeholder="单位（如：月、个）" />
          <u-checkbox v-model="form.negotiable" shape="circle">可议价</u-checkbox>
        </view>
      </view>

      <!-- 位置 -->
      <view class="form-section">
        <text class="label required">位置</text>
        <view class="location-selector" @click="chooseLocation">
          <text v-if="form.location">{{ form.location.address }}</text>
          <text v-else class="placeholder">选择位置</text>
          <u-icon name="arrow-right" size="16"></u-icon>
        </view>
      </view>

      <!-- 发布限制提示 -->
      <view class="limit-tip">
        今日还可发布：{{ userStore.remainingPosts }} 条
      </view>
    </scroll-view>

    <!-- 底部按钮 -->
    <view class="footer">
      <u-button
        v-if="step === 1"
        type="primary"
        :disabled="!selectedCategory"
        @click="nextStep"
      >
        下一步
      </u-button>
      <template v-else>
        <u-button plain @click="prevStep">上一步</u-button>
        <u-button
          type="primary"
          :loading="publishing"
          :disabled="!canPublish"
          @click="handlePublish"
        >
          立即发布
        </u-button>
      </template>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useAppStore } from '@/store/app'
import { useUserStore } from '@/store/user'
import { postApi, uploadApi } from '@/api'
import { chooseImage as chooseImageUtil, chooseVideo as chooseVideoUtil, chooseLocation as chooseLocationUtil } from '@/utils/common'
import type { Category, LocationInfo } from '@/types'

const appStore = useAppStore()
const userStore = useUserStore()

// 状态
const step = ref(1)
const selectedCategory = ref<Category | null>(null)
const selectedSubCategory = ref<Category | null>(null)
const publishing = ref(false)

// 表单数据
const form = ref({
  title: '',
  content: '',
  imageUrls: [] as string[],
  videoUrl: '',
  price: '',
  priceUnit: '',
  negotiable: false,
  location: null as LocationInfo | null
})

// 计算属性
const imageLimit = computed(() => {
  return userStore.isVip ? 9 : 6
})

const subCategories = computed(() => {
  if (!selectedCategory.value) return []
  return appStore.getSubCategories(selectedCategory.value.id)
})

const canPublish = computed(() => {
  return (
    form.value.content.trim() !== '' &&
    (form.value.imageUrls.length > 0 || form.value.videoUrl) &&
    form.value.location !== null &&
    userStore.remainingPosts > 0
  )
})

/**
 * 选择分类
 */
const selectCategory = (category: Category) => {
  selectedCategory.value = category
  selectedSubCategory.value = null
}

/**
 * 下一步
 */
const nextStep = () => {
  if (!selectedCategory.value) {
    uni.showToast({ title: '请选择分类', icon: 'none' })
    return
  }
  step.value = 2
}

/**
 * 上一步
 */
const prevStep = () => {
  step.value = 1
}

/**
 * 选择图片
 */
const chooseImage = async () => {
  try {
    const remaining = imageLimit.value - form.value.imageUrls.length
    const images = await chooseImageUtil(remaining)

    uni.showLoading({ title: '上传中...' })

    // 上传图片
    const uploadPromises = images.map(img => uploadApi.uploadImage(img))
    const urls = await Promise.all(uploadPromises)

    form.value.imageUrls.push(...urls)

    uni.hideLoading()
  } catch (err) {
    uni.hideLoading()
    console.error('选择图片失败:', err)
  }
}

/**
 * 删除图片
 */
const removeImage = (index: number) => {
  form.value.imageUrls.splice(index, 1)
}

/**
 * 选择视频
 */
const chooseVideo = async () => {
  try {
    const videoPath = await chooseVideoUtil(15)

    uni.showLoading({ title: '上传中...' })

    // 上传视频
    const url = await uploadApi.uploadVideo(videoPath)

    form.value.videoUrl = url

    uni.hideLoading()
  } catch (err) {
    uni.hideLoading()
    console.error('选择视频失败:', err)
  }
}

/**
 * 选择位置
 */
const chooseLocation = async () => {
  try {
    const res = await chooseLocationUtil()

    form.value.location = {
      province: '',
      city: '',
      district: '',
      address: res.address,
      lat: res.latitude,
      lng: res.longitude
    }
  } catch (err) {
    console.error('选择位置失败:', err)
  }
}

/**
 * 发布
 */
const handlePublish = async () => {
  if (!canPublish.value) return

  publishing.value = true

  try {
    const data: any = {
      categoryId: selectedCategory.value!.id,
      content: form.value.content.trim(),
      mediaType: form.value.videoUrl ? 'video' : 'image',
      mediaUrls: form.value.videoUrl ? [form.value.videoUrl] : form.value.imageUrls
    }

    if (form.value.title) {
      data.title = form.value.title
    }

    if (selectedSubCategory.value) {
      data.subCategory = selectedSubCategory.value.name
    }

    if (form.value.price) {
      data.priceInfo = {
        price: Number(form.value.price),
        unit: form.value.priceUnit || '元',
        negotiable: form.value.negotiable
      }
    }

    await postApi.create(data)

    // 更新发布次数
    userStore.incrementPostCount()

    uni.showToast({
      title: '发布成功',
      icon: 'success'
    })

    // 返回首页
    setTimeout(() => {
      uni.switchTab({ url: '/pages/index/index' })
    }, 1500)
  } catch (err: any) {
    console.error('发布失败:', err)
    uni.showToast({
      title: err.message || '发布失败',
      icon: 'none'
    })
  } finally {
    publishing.value = false
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-color-page);
}

.content {
  flex: 1;
  padding: var(--spacing-md);
  padding-bottom: 120rpx;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: var(--spacing-md);

  .category-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: var(--spacing-lg);
    background-color: var(--bg-color);
    border-radius: var(--radius-md);
    border: 2rpx solid transparent;

    &.active {
      border-color: var(--primary-color);
      background-color: rgba(86, 119, 252, 0.05);
    }

    .category-icon {
      width: 80rpx;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 48rpx;
      margin-bottom: var(--spacing-sm);
    }

    .category-name {
      font-size: 28rpx;
      color: var(--text-color);
    }
  }
}

.form-section {
  margin-bottom: var(--spacing-lg);

  .label {
    display: block;
    font-size: 28rpx;
    color: var(--text-color);
    margin-bottom: var(--spacing-sm);

    &.required::after {
      content: '*';
      color: var(--error-color);
      margin-left: 8rpx;
    }
  }
}

.sub-category-section {
  margin-bottom: var(--spacing-lg);

  .sub-category-list {
    display: flex;
    flex-wrap: wrap;
    gap: var(--spacing-sm);
    margin-top: var(--spacing-sm);

    .sub-category-item {
      padding: 16rpx 32rpx;
      background-color: var(--bg-color);
      border-radius: var(--radius-round);
      border: 1rpx solid var(--border-color);
      font-size: 28rpx;

      &.active {
        background-color: var(--primary-color);
        color: #ffffff;
        border-color: var(--primary-color);
      }
    }
  }
}

.media-upload {
  .image-list {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16rpx;

    .image-item {
      position: relative;
      padding-bottom: 100%;

      .upload-image {
        position: absolute;
        width: 100%;
        height: 100%;
        border-radius: var(--radius-sm);
      }

      .delete-btn {
        position: absolute;
        top: 8rpx;
        right: 8rpx;
        width: 48rpx;
        height: 48rpx;
        background-color: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .upload-btn {
    position: relative;
    padding-bottom: 100%;
    background-color: var(--bg-color-page);
    border: 2rpx dashed var(--border-color);
    border-radius: var(--radius-sm);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    text {
      font-size: 24rpx;
      color: var(--text-color-placeholder);
      margin-top: 8rpx;
    }
  }
}

.price-input {
  display: flex;
  gap: var(--spacing-sm);
  align-items: center;
}

.location-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-md);
  background-color: var(--bg-color);
  border-radius: var(--radius-sm);

  .placeholder {
    color: var(--text-color-placeholder);
  }
}

.limit-tip {
  text-align: center;
  font-size: 24rpx;
  color: var(--text-color-secondary);
  margin-top: var(--spacing-lg);
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: var(--spacing-md);
  background-color: var(--bg-color);
  border-top: 1rpx solid var(--border-color-light);
  display: flex;
  gap: var(--spacing-md);
}
</style>
